package com.zhukaoguan.boot11.controller;

import com.zhukaoguan.boot11.entity.User;
import com.zhukaoguan.boot11.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/login")
    public int login(User user, String rem, HttpSession session, HttpServletResponse response){
        User u = mapper.select(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                if (rem!=null) {
                    Cookie c1 = new Cookie("username", user.getUsername());
                    c1.setMaxAge(60*60*24*30);
                    Cookie c2 = new Cookie("password", user.getPassword());
                    c2.setMaxAge(60*60*24*30);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                session.setAttribute("user",u);
                return 1;
            }else {
                return 3;
            }
        }
        return 2;
    }
    @RequestMapping("/check")
    public User check(User user,HttpSession session){
        return (User) session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
       session.removeAttribute("user");
    }
}
